package user

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"gopkg.in/go-playground/validator.v8"
	"test_singo/conf"
	"test_singo/models"
	"test_singo/utils"
)

func CurrentUser(c *gin.Context) *models.User {
	if user, exists := c.Get("user"); exists {
		if u, ok := user.(*models.User); ok {
			return u
		}
	}
	return nil
}

func GetUser(id interface{}) (u models.User, err error) {
	var user models.User
	result := models.DB.First(&user, id)
	return user, result.Error
}

func ErrI18n(err error) utils.Response {
	if ve, ok := err.(validator.ValidationErrors); ok {
		for _, e := range ve {
			field := conf.Translate(fmt.Sprintf("Field.%s", e.Field))
			tag := conf.Translate(fmt.Sprintf("Tag.Valid.%s", e.Tag))
			return utils.ParamErr(fmt.Sprintf("%s s%", field, tag), err)
		}
	}

	if _, ok := err.(*json.UnmarshalTypeError); ok {
		return utils.ParamErr("json类型不对", err)
	}

	return utils.ParamErr("参数错误", err)

}